package com.weme.common.util

import android.content.Context
import android.util.Log
import androidx.fragment.app.FragmentActivity
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.weme.common.dialog.PermissingDialog
import com.weme.common.luban.Luban
import io.reactivex.Flowable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers

import java.io.File


object MediaUtils {
    fun selectImages(context: FragmentActivity, imageSize: Int, callback: (String) -> Unit) {
        if (XXPermissions.isGranted(context, Permission.WRITE_EXTERNAL_STORAGE)) { //isPermanentDenied
            PictureSelector.create(context).openGallery(SelectMimeType.ofImage()).setMaxSelectNum(imageSize).isPreviewImage(false).setImageEngine(GlideEngine()).forResult(imageResultCallbackListener(context, callback))
        } else {
            val permissingDialog = PermissingDialog(context, mutableListOf<String>(Permission.WRITE_EXTERNAL_STORAGE)) {
                PictureSelector.create(context).openGallery(SelectMimeType.ofImage()).setMaxSelectNum(imageSize).isPreviewImage(false).setImageEngine(GlideEngine()).forResult(imageResultCallbackListener(context, callback))
            }
            permissingDialog.show(context.supportFragmentManager, "")
        }
    }

    fun selectVideos(context: FragmentActivity, imageSize: Int, callback: (String) -> Unit) {
        if (XXPermissions.isGranted(context, Permission.WRITE_EXTERNAL_STORAGE)) {
            PictureSelector.create(context).openGallery(SelectMimeType.ofVideo()).setMaxSelectNum(imageSize).isPreviewImage(false).setFilterVideoMaxSecond(30).setFilterVideoMinSecond(3).setImageEngine(GlideEngine()).forResult(videoResultCallbackListener(context, callback))
        } else {
            val permissingDialog = PermissingDialog(context, mutableListOf<String>(Permission.WRITE_EXTERNAL_STORAGE)) {
                PictureSelector.create(context).openGallery(SelectMimeType.ofVideo()).setMaxSelectNum(imageSize).isPreviewImage(false).setFilterVideoMaxSecond(30).setFilterVideoMinSecond(3).setImageEngine(GlideEngine()).forResult(videoResultCallbackListener(context, callback))
            }
            permissingDialog.show(context.supportFragmentManager, "") //            permissingDialog.setPermission(context, Permission.WRITE_EXTERNAL_STORAGE) {
            //                PictureSelector.create(context).openGallery(SelectMimeType.ofVideo()).setMaxSelectNum(imageSize).isPreviewImage(false).setCompressEngine(getCompressEngine(context)).setImageEngine(GlideEngine()).forResult(resultCallbackListener(context, callback))
            //            }

        }
    }

    fun captureImage(context: FragmentActivity, callback: (String) -> Unit) {
        if (XXPermissions.isGranted(context, Permission.CAMERA)) {
            PictureSelector.create(context).openCamera(SelectMimeType.ofImage())

                .forResult(imageResultCallbackListener(context, callback))
        } else {
            val permissingDialog = PermissingDialog(context, mutableListOf<String>(Permission.CAMERA)) {
                PictureSelector.create(context).openCamera(SelectMimeType.ofImage())

                    .forResult(imageResultCallbackListener(context, callback))
            }
            permissingDialog.show(context.supportFragmentManager, "") //            permissingDialog.setPermission(context, Permission.CAMERA) {
            //                PictureSelector.create(context).openCamera(SelectMimeType.ofImage()).setCompressEngine(getCompressEngine(context))
            //
            //                    .forResult(resultCallbackListener(context, callback))  }

        }
    }

    fun captureVideo(context: FragmentActivity, callback: (String) -> Unit) {
        if (XXPermissions.isGranted(context, Permission.WRITE_EXTERNAL_STORAGE)) {
            PictureSelector.create(context).openCamera(SelectMimeType.ofVideo()).setRecordVideoMinSecond(5).setRecordVideoMaxSecond(30).forResult(videoResultCallbackListener(context, callback))
        } else {
            val permissingDialog = PermissingDialog(context, mutableListOf<String>(Permission.WRITE_EXTERNAL_STORAGE)) {
                PictureSelector.create(context).openCamera(SelectMimeType.ofVideo()).setRecordVideoMinSecond(5).setRecordVideoMaxSecond(30).forResult(videoResultCallbackListener(context, callback))
            }
            permissingDialog.show(context.supportFragmentManager, "") //            permissingDialog.setPermission(context, Permission.WRITE_EXTERNAL_STORAGE) {
            //                PictureSelector.create(context).openCamera(SelectMimeType.ofVideo()).setCompressEngine(getCompressEngine(context)).forResult(resultCallbackListener(context, callback))
            //            }
        }
    }

    private fun requestPermissions(context: FragmentActivity, callback: () -> Unit) {
        XXPermissions.with(context).permission(Permission.CAMERA).permission(Permission.READ_MEDIA_IMAGES).permission(Permission.READ_MEDIA_VIDEO).permission(Permission.READ_MEDIA_AUDIO).permission(Permission.WRITE_EXTERNAL_STORAGE) //  .permission(Permission.REQUEST_PERMISSIONS)
            .request(object : OnPermissionCallback {
                override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                    if (allGranted) {
                        callback.invoke()
                    }
                }

                override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) { // Handle denied permissions
                }
            })
    }

    private var disposable: Disposable? = null

    private fun imageResultCallbackListener(context: Context, callback: (String) -> Unit) = object : OnResultCallbackListener<LocalMedia> {
        override fun onResult(result: ArrayList<LocalMedia>?) {
            result?.let {
                if (it.isNotEmpty()) {
                    val filePath = it[0].realPath
                    Log.e("tag", "视频或图片大小" + getFileSize(filePath))
                    disposable = Flowable.just(filePath).observeOn(Schedulers.io()).map {
                        Luban.with(context).load(it).get()
                    }.observeOn(AndroidSchedulers.mainThread()).subscribe({ compressedFiles ->
                        Log.e("tag", "压缩后的图片大小" + getFileSize(compressedFiles[0].absolutePath))
                        compressedFiles?.firstOrNull()?.absolutePath?.let(callback::invoke)
                    }, { error -> // 处理发生的错误
                        // 在主线程中执行
                        error.printStackTrace()
                        callback.invoke("")

                    })
                }
            }
        }

        override fun onCancel() { // 处理取消操作
        }
    }


    private fun videoResultCallbackListener(context: Context, callback: (String) -> Unit) = object : OnResultCallbackListener<LocalMedia> {
        override fun onResult(result: ArrayList<LocalMedia>?) {
            result?.let {
                if (it.isNotEmpty()) {
                    val filePath = it[0].realPath
                    callback.invoke("start")
                    VideoCompressUtils.startCompressed(context, filePath, object : VideoCompressUtils.IAddCompressDateListener {
                        override fun dateBank(s: String) {
                            Log.e("tag", "压缩后的视频大小" + getFileSize(s))
                            getFileSize(s)
                            callback.invoke(s)
                        }

                        override fun errorBean(s: String) {
                            Log.e("tag", "视频压缩失败" + getFileSize(s))
                            callback.invoke(s)
                        }

                    })
                }
            }
        }

        override fun onCancel() { // 处理取消操作
        }
    }


    //    private fun getCompressEngine(): CompressFileEngine {
    //        return CompressFileEngine { context, source, call ->
    //            Luban.with(context).load(source[0]).setCompressListener(object : OnCompressListener {
    //                override fun onStart() { // Compression started
    //
    //                    Log.e("tag",getFileSize(source[0].encodedPath!!).toString())
    //                }
    //
    //                override fun onSuccess(file: File?) {
    //                    if (call != null && file != null) {
    //
    //                        call.onCallback("", file.absolutePath)
    //                    }
    //                }
    //
    //                override fun onError(e: Throwable?) {
    //                    if (call != null) {
    //
    //                        // Handle compression error
    //                    }
    //                }
    //            }).launch()
    //        }
    //    }


    fun getFileSize(filePath: String): Long {
        val file = File(filePath)
        return if (file.exists() && file.isFile) {
            file.length() // 返回文件大小，单位是字节
        } else {
            -1 // 文件不存在或不是一个有效的文件
        }
    }
}
